package no.ntnu.fp.messages.impl;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Appointment;
import no.ntnu.fp.utils.XmlParser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AppointmentAddedOrUpdatedMessage implements Message {
	private final Appointment appointment;
	
	public AppointmentAddedOrUpdatedMessage() {
		this(null);
	}
	
	public AppointmentAddedOrUpdatedMessage(Appointment appointment) {
		this.appointment = appointment;
	}

	public Appointment getAppointment() {
		return appointment;
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.APPOINTMENT_ADDED_OR_UPDATED_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document dom = XmlParser.parseXmlString(xml);
		Element appointmentElement = (Element)dom.getElementsByTagName("appointment").item(0);
		Appointment appointment = new Appointment(appointmentElement);
		return new AppointmentAddedOrUpdatedMessage(appointment);
	}
	
	@Override
	public String toString() {
		Document dom = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element root = dom.createElement("message");
		Element appointmentElement = this.appointment.toXml(dom);
		root.appendChild(appointmentElement);
		return getMessageCode() + XmlParser.convertXmlToString(root);
	}
}
